import React from "react";
import style from "../../style/Dashboard.module.scss";
import { Input, Space, DatePicker, Select, Button, Table } from "antd";
import { Route } from "react-router-dom";
import { useEffect, useState, useRef, useCallback } from "react";
import "dayjs/locale/zh-cn";
import locale from "antd/es/date-picker/locale/zh_CN"; //默认为中文
import { getUser } from "../../api/User";

const { RangePicker } = DatePicker;
function DashboardContent() {
  const onChangeAction = (value) => {
    setchange(value);
    console.log(`selected ${value}`); //用户选择事件
  };

  const [id, setid] = useState(""); //id
  const [RegTime, setRegTime] = useState(""); //注册时间
  const [search, setsearch] = useState(""); //搜索
  const [change, setchange] = useState("");
  const [cons1, setcons1] = useState(""); //消费金额1
  const [cons2, setcons2] = useState(""); //消费金额2
  const [goods1, setgoods1] = useState(""); //订单数量1
  const [goods2, setgoods2] = useState(""); //订单数量2

  const IdRef = useRef(); //id
  const cons1Ref = useRef(); //消费金额1
  const cons2Ref = useRef(); //消费金额2

  const goods1Ref = useRef(); //消费金额1
  const goods2Ref = useRef(); //消费金额2

  const n = useCallback((value) => {
    setRegTime(value);
  }, []);

  //获取id搜索框的内容
  const userChang = useCallback(() => {
    setid(IdRef.current.input.value);
  }, []);

  //获取消费金额1的内容
  const cons1Chang = useCallback(() => {
    setcons1(cons1Ref.current.input.value);
  }, []);
  //获取消费金额2的内容
  const cons2Chang = useCallback(() => {
    setcons2(cons2Ref.current.input.value);
  }, []);

  //获取订单数量1的内容
  const goods1Chang = useCallback(() => {
    setgoods1(goods1Ref.current.input.value);
  }, []);
  //获取订单数量2的内容
  const goods2Chang = useCallback(() => {
    setgoods2(goods2Ref.current.input.value);
  }, []);

  //查询功能
  const SreachAction = useCallback(() => {
    let aaa = ""; //查询出的数据暂存在aaa
    //判断id/用户名/手机号
    if (id) {
      const res = data.filter(
        (item) =>
          item._id === id ||
          item.telephone === Number(id) ||
          item.username === id
      );
      setsearch(res);
      aaa = res;
      // console.log(aaa);
    }
    // console.log(search);
    //判断注册时间
    if (RegTime) {
      const reg1 = new Date(RegTime[0].$d).getTime();
      const reg2 = new Date(RegTime[1].$d).getTime();
      const res = (aaa ? aaa : data).filter(
        (item) =>
          // console.log(reg1, reg2, new Date(item.RegTime).getTime())
          new Date(item.RegTime).getTime() > reg1 &&
          new Date(item.RegTime).getTime() < reg2
      );
      setsearch(res);
      aaa = res;
    }
    //判断消费金额
    if (cons1 && cons2) {
      // console.log(cons1, cons2);
      const res = (aaa ? aaa : data).filter(
        (item) =>
          // console.log(item)
          item.consumption >= cons1 && item.consumption <= cons2
      );
      setsearch(res);
      aaa = res;
    }
    //判断订单数量
    if (goods1 && goods2) {
      console.log(goods1, goods2);
      const res = (aaa ? aaa : data).filter(
        (item) =>
          // console.log(item)
          item.goods >= goods1 && item.goods <= goods2
      );
      setsearch(res);
      aaa = res;
    } else {
      return;
    }
  }, [id, RegTime, search, cons1, cons2, goods1, goods2]);

  //重置功能
  const resetAction = useCallback(() => {
    setsearch("");
  }, []);

  /* ----------------------------引用table组--------------------------- */
  const columns = [
    {
      title: "用户ID",
      dataIndex: "_id",
      render: (_id) => `${_id}`,
    },
    {
      title: "用户名",
      dataIndex: "username",
      render: (username) => `${username}`,
      width: "20%",
    },
    {
      title: "手机号",
      dataIndex: "telephone",
      render: (telephone) => `${telephone}`,
    },
    {
      title: "注册时间",
      dataIndex: "RegTime",
      render: (RegTime) => `${RegTime}`,
    },
    {
      title: "最近登录时间",
      dataIndex: "RegTime",
      render: (RegTime) => `${RegTime}`,
    },
    {
      title: "消费金额",
      dataIndex: "consumption",
      render: (consumption) => `${consumption}`,
    },
    {
      title: "订单数量",
      dataIndex: "goods",
      render: (goods) => `${goods}`,
    },
  ];
  const getRandomuserParams = (params) => ({
    results: params.pagination?.pageSize,
    page: params.pagination?.current,
    ...params,
  });

  const [data, setData] = useState();
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  useEffect(() => {
    fetchData();
  }, [search]);
  const fetchData = async () => {
    await getRandomuserParams(tableParams);
    try {
      const results = await getUser();
      setLoading(true);
      setData(results.data.msg);

      setLoading(false);
      setTableParams({
        ...tableParams,
        pagination: {
          ...tableParams.pagination,
          total: data,
        },
      });
      console.log(data);
    } catch (error) {
      console.log(error);
    }
  };

  const handleTableChange = (pagination, filters, sorter) => {
    setTableParams({
      pagination,
      filters,
      ...sorter,
    });

    // `dataSource` is useless since `pageSize` changed
    if (pagination.pageSize !== tableParams.pagination?.pageSize) {
      setData([]);
    }
  };
  /* ------------------------------------------------------------ */

  return (
    <div className={style.Dashboard}>
      <div className={style.box}>
        <div className="first">
          <Input
            placeholder="用户ID/手机号/用户昵称"
            style={{ width: "50vh", margin: "20px 20px " }}
            onChange={userChang}
            ref={IdRef}
          />
          {/*获取用户信息 */}
          <Space
            direction="vertical"
            style={{ width: "50vh", margin: "20px 20px " }}
          >
            <RangePicker
              onChange={n}
              showTime
              locale={locale}
              placeholder={["注册时间", "注册时间"]}
            />
          </Space>
          {/* 获取用户注册时间 */}
          <Select
            showSearch
            placeholder="是否交易"
            optionFilterProp="children"
            style={{ width: "20vh" }}
            onChange={onChangeAction}
            filterOption={(input, option) =>
              (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
            }
            options={[
              {
                value: "true",
                label: "是",
              },
              {
                value: "false",
                label: "否",
              },
            ]}
          />
        </div>
        <div className="second">
          <Space.Compact
            size="middle"
            style={{ width: "50vh", margin: "0px 20px 20px 20px " }}
          >
            <Input
              placeholder="消费金额"
              onChange={cons1Chang}
              ref={cons1Ref}
            />
            <Input
              placeholder="消费金额"
              onChange={cons2Chang}
              ref={cons2Ref}
            />
          </Space.Compact>
          {/* 筛选用户消费金额范围 */}
          <Space.Compact
            size="middle"
            style={{ width: "50vh", margin: "0px 20px 20px 20px " }}
          >
            <Input
              placeholder="订单数量"
              onChange={goods1Chang}
              ref={goods1Ref}
            />
            <Input
              placeholder="订单数量"
              onChange={goods2Chang}
              ref={goods2Ref}
            />
          </Space.Compact>
          <Button
            type="primary"
            style={{ backgroundColor: "#666666" }}
            onClick={SreachAction}
          >
            查询
          </Button>
          <Button style={{ margin: "10px" }} onClick={resetAction}>
            重置
          </Button>
        </div>
      </div>
      <Table
        columns={columns}
        rowKey={({ _id }) => _id}
        dataSource={search ? search : data}
        pagination={tableParams.pagination}
        loading={loading}
        onChange={handleTableChange}
      />
    </div>
  );
}

export default function Dashboard({ route: { routes } }) {
  // console.log(routes);
  return (
    <>
      <Route exact path="/" component={DashboardContent} />
      {/* 
      <Switch>
        <Route path="/product/manager/add" component={Add} />
      </Switch>
     */}
    </>
  );
}
